<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined ( '_JEXEC' ) or die ();

jimport ( 'joomla.application.component.model' );

class JAJobBoardModeljaTransactions extends JModel {
	
	var $_data;
	var $_table;
	var $_pagination;
	var $_fieldListEdit;
	var $_table_name = 'ja_transactions';
	
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'JA_Transactions', 'JobBoardTable' );
		}
		return $this->_table;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_resumes Table object
	 */
	function getItem() {
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		
		$table = & $this->_getTable ();
		$table->_tbl_key = 'id';
		
		// Load the current item if it has been defined
		$edit = JRequest::getVar ( 'edit', true );
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		
		if ($edit) {
			$table->load ( $cid [0] );
			$table->cleanData ();
		}
		$item = $table;
		
		return $item;
	}
	
	function getItems() {
		global $mainframe;
		$statistics = array ();
		$statistics ['completed'] = JRequest::getVar ( 'filter_completed' );
		$statistics ['created_date'] = JRequest::getVar ( 'filter_duration' );
		$filter_order = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jatransactions.filter_order", 'filter_order', 'id', 'cmd' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jatransactions.filter_order_Dir", 'filter_order_Dir', 'DESC', 'word' );
		$search = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jatransactions.search", 'search', '', 'string' );
		$search = JString::strtolower ( $search );
		$task = JRequest::getVar ( 'task' );
		$userid = JRequest::getVar ( 'userid' );
		$filter_status = JRequest::getVar ( 'filter_status' );
		$limit = JRequest::getVar ( 'limit' );
		$old_limit = JRequest::getVar ( 'old_limit' );
		
		$limitstart = JRequest::getVar ( 'limitstart' );
		if ($limit != $old_limit)
			$limitstart = 0;
		$db = JFactory::getDBO ();
		$filter_credit_invoice = JRequest::getVar ( 'filter_credit_invoice' );
		if ($filter_order) {
			$orderby = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY id DESC';
		}
		
		$where = array ();
		
		if ($statistics ['completed']) {
			$where [] = '(a.completed=' . $statistics ['completed'] . ')';
		}
		switch ($statistics ['created_date']) {
			case 'today' :
				$where [] = '(DATEDIFF(a.created_date,now())=0)';
				break;
			case 'week' :
				$where [] = '(EXTRACT(WEEK FROM a.created_date)=EXTRACT(WEEK FROM now()))';
				break;
			case 'month' :
				$where [] = '(EXTRACT(MONTH FROM a.created_date)=EXTRACT(MONTH FROM now()))';
				break;
		}
		
		if (is_array ( $filter_credit_invoice ))
			foreach ( $filter_credit_invoice as $fieldname => $value )
				$where [] = '(' . $fieldname . '=' . $value . ')';
		if ($search) {
			$where [] = " (b.name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
		}
		if (($filter_status != null) && ($filter_status != ''))
			$where [] = '(a.completed="' . $filter_status . '")';
		if ($task == 'trans_viewbyuser')
			$where [] = 'a.user_id=' . $userid;
		
		$where_clause = implode ( ' AND ', $where );
		$query = 'SELECT a.*,b.name FROM #__ja_transactions AS a LEFT JOIN #__users as b ON a.user_id=b.id ';
		if ($where_clause)
			$query .= ' WHERE ' . $where_clause;
		if ($orderby)
			$query .= $orderby;
		$query_count = 'SELECT a.id FROM #__ja_transactions as a ';
		if ($where_clause)
			$query_count .= ' WHERE ' . $where_clause;
		jimport ( 'joomla.html.pagination' );
		$db->setQuery ( $query_count );
		$items = $db->loadObjectList ();
		$pageNav = new JPagination ( count ( $items ), $limitstart, $limit );
		$db->setQuery ( $query, $limitstart, $limit );
		$items = $db->loadObjectList ();
		$paymentObject = get_payment_gateways ();
		for($i = 0; $i < count ( $items ); $i ++) {
			for($j = 0; $j < count ( $paymentObject ); $j ++) {
				if ($items [$i]->payment_method == $paymentObject [$j]->id)
					$items [$i]->payment_name = $paymentObject [$j]->alias;
			
			}
			if (! isset ( $items [$i]->payment_name ))
				$items [$i]->payment_name = '';
			switch (strtolower ( $items [$i]->product_type )) {
				case 'c' :
					$items [$i]->product_name = $this->getProductNamefromID ( 'ja_credits', $items [$i]->product_id );
					break;
				case 'p' :
					$items [$i]->product_name = $this->getProductNamefromID ( 'ja_posting_plans', $items [$i]->product_id );
					break;
				case 's' :
					$items [$i]->product_name = $this->getProductNamefromID ( 'ja_subscriptions', $items [$i]->product_id );
					break;
			}
			if ($items [$i]->completed)
				$items [$i]->status_name = 'Completed';
			else {
				$items [$i]->status_name = 'Uncompleted';
			}
		
		}
		
		$this->_pagination = $pageNav;
		return $items;
	}
	
	function getProductNamefromID($table_name, $product_id) {
		$db = JFactory::getDBO ();
		$query = "SELECT title FROM #__$table_name WHERE id=$product_id";
		$db->setQuery ( $query );
		$id = $db->loadObject ();
		if (isset ( $id->title ))
			return $id->title;
		else
			return '';
	}
	
	function getIDfromInvoice_id($table_name, $invoice_id) {
		$db = JFactory::getDBO ();
		$query = "SELECT id FROM #__$table_name WHERE invoice_id=$invoice_id";
		$db->setQuery ( $query );
		$id = $db->loadObject ();
		return $id->id;
	}
	
	function getPagination() {
		if (! $this->_pagination)
			$this->getItems ();
		return $this->_pagination;
	}
	
	function store() {
		// Initialize variables
		require_once(JPATH_COMPONENT_SITE.DS.'models'.DS.'japayment.php');
		$model_payment = new JobBoardModelJAPayment();
		global $jbconfig;
		$user = & JFactory::getUser ();
		$db = & JFactory::getDBO ();
		$row = & $this->getItem ();
		if ($row->id) {
			$old_row = new stdClass ( );
			$old_row->product_type = $row->product_type;
			$old_row->value = $row->value;
			$old_row->value_type = $row->value_type;
			$old_row->product_id = $row->product_id;
		}
		$pre_id = $row->id;
		$pre_status = $row->completed;
		$post = JRequest::getVar ( 'arr_invoice_data' );
		if ($post) {
			foreach ( $post as $k => $value ) {
				if ($k != 'cid' && is_array ( $value )) {
					$post [$k] = implode ( ',', $value );
				}
			}
		}		
		
		if (! $post)	$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
		
		if (! isset($post['ip']) || !$post['ip'])		$post['ip'] = $_SERVER ['REMOTE_ADDR'];
		
		if (! $row->bind ( $post )) {
			return false;
		}
		
		if (! ($temp = $row->store ())) {
			
			return false;
		}
		$new_status = $row->completed;
		if ($pre_id == null) {
			$model_payment->email_posting_order_wait ( 'email_posting_plan_pending', $row, $row->product_id, $row->product_type, $row->user_id );
			if ($jbconfig ['emails']->get ( 'fromemail' ))
				$model_payment->admin_email_posting_order_wait ('AdminMailNewOrder', $row, $row->product_id, $row->product_type, $row->user_id );
			if ($new_status == 1) {
				$model_payment->email_posting_order_completed ( $row, $row->product_id, 'email_posting_plan_completed', $row->product_type );
				if ($jbconfig ['emails']->get ( 'fromemail' ))
					$model_payment->admin_email_posting_order_completed ( $row, $row->product_id, 'adminmailcompletedorder', $row->product_type );
				$this->updateAccount ( $row->user_id, $row->product_id, $row->product_type, false, $row );
			}
		} else {
			if (($new_status == 1) && ($pre_status != $new_status)) {
				$model_payment->email_posting_order_completed ( $row, $row->product_id, 'email_posting_plan_completed', $row->product_type );
				if ($jbconfig ['emails']->get ( 'fromemail' ))
					$model_payment->admin_email_posting_order_completed ( $row, $row->product_id, 'adminmailcompletedorder', $row->product_type );
				$this->updateAccount ( $row->user_id, $row->product_id, $row->product_type, true, $row );
			} elseif (($new_status == 0) && ($pre_status != $new_status)) {
				$model_payment->email_posting_order_wait ( 'email_posting_plan_pending', $row, $row->product_id, $row->product_type, $row->user_id );
				if ($jbconfig ['emails']->get ( 'fromemail' ))
					$model_payment->admin_email_posting_order_wait ('AdminMailNewOrder', $row, $row->product_id, $row->product_type, $row->user_id );
				$this->revertTransaction ( $row->user_id, $row->product_id, $row->product_type, $new_status, $row );
			}
		}
		if (($new_status == 1) && ($pre_status == $new_status) && ($row->product_id != $old_row->product_id))
			$this->updateAccount_change_product ( $row, $old_row );
		return $row->id;
	}
	
	function updateAccount_change_product($transaction, $old_transaction) {
		$account = getAccountByUserID ( $transaction->user_id );
		$vars = new stdClass ( );
		switch (strtolower ( $transaction->product_type )) {
			case 'p' :
				{
					
					$plan_item = getItemByFieldName ( 'ja_posting_plans', 'id', $transaction->product_id );
					
					switch ($plan_item [0]->type) {
						
						case 'standard' :
							$vars->standard_posts_balance = $plan_item [0]->value + ( int ) $account->standard_posts_balance;
							break;
						case 'premium' :
							
							$vars->premium_posts_balance = $plan_item [0]->value + ( int ) $account->premium_posts_balance;
							break;
						case 'resume' :
							$end_date = $account->end_date_search_resume;
							if ($end_date != '') {
								$end_date = getdate ( strtotime ( $end_date ) );
								$time_end_date = $end_date [0];
								if (time () < $time_end_date) {
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( $end_date ['hours'], $end_date ['minutes'], $end_date ['seconds'], $end_date ['mon'], $end_date ['mday'] + $plan_item [0]->value, $end_date ['year'] ) );
								} else {
									$vars->begin_date_search_resume = date ( 'Y-m-d H:i:s' );
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( date ( 'H' ), date ( 'i' ), date ( 's' ), date ( 'm' ), date ( 'd' ) + $plan_item [0]->value, date ( 'Y' ) ) );
								}
							}
							break;
					}
				}
				break;
			case 'c' :
				{
					$credit_item = getItemByFieldName ( 'ja_credits', 'id', $transaction->product_id );
					
					$vars->credit_balance = $credit_item [0]->value + ( int ) $account->credit_balance;
				}
				break;
			case 's' :
				{
				}
				break;
		}
		switch (strtolower ( $old_transaction->product_type )) {
			case 'p' :
				{
					switch ($old_transaction->value_type) {
						
						case 'standard' :
							$vars->standard_posts_balance = ( int ) $account->standard_posts_balance - $old_transaction->value;
							break;
						case 'premium' :
							
							$vars->premium_posts_balance = ( int ) $account->premium_posts_balance - $old_transaction->value;
							break;
						case 'resume' :
							$end_date = $account->end_date_search_resume;
							if ($end_date != '') {
								$end_date = getdate ( strtotime ( $end_date ) );
								$time_end_date = $end_date [0];
								if (time () < $time_end_date) {
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( $end_date ['hours'], $end_date ['minutes'], $end_date ['seconds'], $end_date ['mon'], $end_date ['mday'] - $old_transaction->value, $end_date ['year'] ) );
								} else {
									$vars->begin_date_search_resume = date ( 'Y-m-d H:i:s' );
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( date ( 'H' ), date ( 'i' ), date ( 's' ), date ( 'm' ), date ( 'd' ) - $old_transaction->value, date ( 'Y' ) ) );
								}
							}
							break;
					}
				}
				break;
			case 'c' :
				{
					$vars->credit_balance = ( int ) $account->credit_balance - $old_transaction->value;
				}
				break;
			case 's' :
				{
				}
				break;
		}
		$vars->user_id = $transaction->user_id;
		$result = update_account_for_employer ( $vars );
	}
	
	function updateAccount($user_id, $product_id, $product_type, $edit = false, $row = null) {
		
		$account = getAccountByUserID ( $user_id );
		$vars = new stdClass ( );
		if (! $edit) {
			switch (strtolower ( $product_type )) {
				case 'p' :
					{
						
						$plan_item = getItemByFieldName ( 'ja_posting_plans', 'id', $product_id );
						
						switch ($plan_item [0]->type) {
							
							case 'standard' :
								$vars->standard_posts_balance = $plan_item [0]->value + ( int ) $account->standard_posts_balance;
								break;
							case 'premium' :
								
								$vars->premium_posts_balance = $plan_item [0]->value + ( int ) $account->premium_posts_balance;
								break;
							case 'resume' :
								$end_date = $account->end_date_search_resume;
								if ($end_date != '') {
									$end_date = getdate ( strtotime ( $end_date ) );
									$time_end_date = $end_date [0];
									if (time () < $time_end_date) {
										$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( $end_date ['hours'], $end_date ['minutes'], $end_date ['seconds'], $end_date ['mon'], $end_date ['mday'] + $plan_item [0]->value, $end_date ['year'] ) );
									} else {
										$vars->begin_date_search_resume = date ( 'Y-m-d H:i:s' );
										$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( date ( 'H' ), date ( 'i' ), date ( 's' ), date ( 'm' ), date ( 'd' ) + $plan_item [0]->value, date ( 'Y' ) ) );
									}
								}
								break;
						}
					}
					break;
				case 'c' :
					{
						$credit_item = getItemByFieldName ( 'ja_credits', 'id', $product_id );
						
						$vars->credit_balance = $credit_item [0]->value + ( int ) $account->credit_balance;
					}
					break;
				case 's' :
					{
					}
					break;
			}
		} else {
			switch (strtolower ( $product_type )) {
				case 'p' :
					{
						switch ($row->value_type) {
							case 'standard' :
								$vars->standard_posts_balance = $row->value + ( int ) $account->standard_posts_balance;
								break;
							case 'premium' :
								
								$vars->premium_posts_balance = $row->value + ( int ) $account->premium_posts_balance;
								break;
							case 'resume' :
								$end_date = $account->end_date_search_resume;
								if ($end_date != '') {
									$end_date = getdate ( strtotime ( $end_date ) );
									$time_end_date = $end_date [0];
									if (time () < $time_end_date) {
										$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( $end_date ['hours'], $end_date ['minutes'], $end_date ['seconds'], $end_date ['mon'], $end_date ['mday'] + $row->value, $end_date ['year'] ) );
									} else {
										$vars->begin_date_search_resume = date ( 'Y-m-d H:i:s' );
										$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( date ( 'H' ), date ( 'i' ), date ( 's' ), date ( 'm' ), date ( 'd' ) + $row->value, date ( 'Y' ) ) );
									}
								}
								break;
						}
					}
					break;
				case 'c' :
					{
						$vars->credit_balance = $row->value + ( int ) $account->credit_balance;
					}
					break;
				case 's' :
					{
					}
					break;
			}
		}
		
		$vars->user_id = $user_id;
		
		$result = update_account_for_employer ( $vars );
	
	}
	
	function revertTransaction($user_id, $product_id, $product_type, $status = 0, $row) {
		//		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		//		JArrayHelper::toInteger($cid, array(0));
		$account = getAccountByUserID ( $user_id );
		$vars = new stdClass ( );
		
		switch (strtolower ( $product_type )) {
			case 'p' :
				{
					switch ($row->value_type) {
						
						case 'standard' :
							$vars->standard_posts_balance = ( int ) $account->standard_posts_balance - $row->value;
							break;
						case 'premium' :
							
							$vars->premium_posts_balance = ( int ) $account->premium_posts_balance - $row->value;
							break;
						case 'resume' :
							$end_date = $account->end_date_search_resume;
							if ($end_date != '') {
								$end_date = getdate ( strtotime ( $end_date ) );
								$time_end_date = $end_date [0];
								if (time () < $time_end_date) {
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( $end_date ['hours'], $end_date ['minutes'], $end_date ['seconds'], $end_date ['mon'], $end_date ['mday'] - $row->value, $end_date ['year'] ) );
								} else {
									$vars->begin_date_search_resume = date ( 'Y-m-d H:i:s' );
									$vars->end_date_search_resume = date ( 'Y-m-d H:i:s', mktime ( date ( 'H' ), date ( 'i' ), date ( 's' ), date ( 'm' ), date ( 'd' ) - $row->value, date ( 'Y' ) ) );
								}
							}
							break;
					}
				}
				break;
			case 'c' :
				{
					$vars->credit_balance = ( int ) $account->credit_balance - $row->value;
				}
				break;
			case 's' :
				{
				}
				break;
		}
		
		$vars->user_id = $user_id;
		$result = update_account_for_employer ( $vars );
		if ($status == 0) {
			$db = JFactory::getDBO ();
			$query = "UPDATE #__ja_transactions SET reason='Reverse',completed=0,processed_date='" . date ( 'Y-m-d H:i:s' ) . "' WHERE id=$row->id";
			$db->setQuery ( $query );
			$db->query ();
		}
	}
	
	function remove() {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		if ($n) {
			$query = "DELETE FROM #__ja_transactions WHERE id = " . implode ( " OR id = ", $cid );
			$db = &JFactory::getDBO ();
			$db->setQuery ( $query );
			return $db->queryBatch ();
		}
		return 1;
	}
	

	
	function getUserList() {
		global $mainframe, $jbconfig;
		
		$db = JFactory::getDBO ();
		$search	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.search",			'user_search',			'',				'string' );
		$search = trim(JString::strtolower ( $search ));
		$where = '';
		require_once (JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'jaemployers.php');
		require_once (JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'jacandidates.php');
		$em_model = new JAJobBoardModelJAEmployers ( );
		$ca_model = new JAJobBoardModeljacandidates ( );
		$employer_list = $em_model->getItems ();
		$user_list = array ();
		if ($search) {
			$where .= " and (";
			$where .= " (name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (id LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= ")";
		}
		$temp_user_id = array ();
		for($i = 0; $i < count ( $employer_list ); $i ++) {
			if ($employer_list [$i]->id)
				$temp_user_id [] = $employer_list [$i]->id;
		}
		if (count ( $temp_user_id ) > 0)
			$temp = implode ( ',', $temp_user_id );
		else
			$temp = '';
		
		if ($temp) {
			$query = "SELECT * FROM #__users WHERE id in ($temp)" . $where;
			$db->setQuery ( $query );
			$temp_user_id = $db->loadObjectList ();
			for($i = 0; $i < count ( $temp_user_id ); $i ++) {
				$temp_user_id [$i]->user_type = JText::_ ( 'Employer' );
				$user_list [] = $temp_user_id [$i];
			}
		}	

		return $user_list;
	}
	
	function getProducts() {
		global $config;
		$db = JFactory::getDBO ();
		$where = '';
		$product_list = array ();
		$search = JRequest::getVar ( 'product_search' );
		if ($search) {
			$where .= " and (";
			$where .= " (title LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= " or (description LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= ")";
		}
		$query = "SELECT * FROM #__ja_posting_plans WHERE published=1" . $where;
		$db->setQuery ( $query );
		$post_list = $db->loadObjectList ();
		for($i = 0; $i < count ( $post_list ); $i ++) {
			$post_list [$i]->t_type = 'P';
			switch ($post_list [$i]->type) {
				case 'standard' :
					$post_list [$i]->product_type = JText::_ ( 'Standard post job' );
					break;
				case 'premium' :
					$post_list [$i]->product_type = JText::_ ( 'Premium post job' );
					break;
				case 'resume' :
					$post_list [$i]->product_type = JText::_ ( 'Search resume' );
					break;
			}
			$product_list [] = $post_list [$i];
		}
		
		$where = '';
		if ($search) {
			$where .= " and (";
			$where .= " (title LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
			$where .= ")";
		}
		$query = "SELECT * FROM #__ja_credits WHERE published=1" . $where;
		$db->setQuery ( $query );
		$credit_list = $db->loadObjectList ();
		for($i = 0; $i < count ( $credit_list ); $i ++) {
			$credit_list [$i]->product_type = JText::_ ( 'Credit' );
			$credit_list [$i]->t_type = 'C';
			$product_list [] = $credit_list [$i];
		}
		return $product_list;
	}
	

	
	function check_user() {
		if (!is_numeric(JRequest::getVar('user_id')))
			return false;
		$user = JFactory::getUser ( JRequest::getInt ( 'user_id' ) );
		if ($user->id) {
			return true;
		} else
			return false;
	}
	
	function getProductInfo() {
		$db = JFactory::getDBO ();
		$product_type = JRequest::getVar ( 'product_type' );
		switch ($product_type) {
			case 'P' :
				$table_name = '#__ja_posting_plans';
				break;
			case 'C' :
				$type = '';
				$table_name = '#__ja_credits';
				break;
			default :
				$type = '';
				$table_name = '#__ja_subscriptions';
				break;
		}
		$query = "SELECT * FROM $table_name WHERE published=1 and id=" . JRequest::getVar ( 'product_id' );
		$db->setQuery ( $query );
		$result = $db->loadObject ();
		if ($product_type == 'P')
			$type = $result->type;
		$text = $result->price . '_' . $type . '_' . $result->value;
		return $text;
	}

}
?>